<template>
	<view class="mine-face">
		<image v-if="userToken" class="mine-face-image" :src="tempFilePath || userInfo.avatar.file_path" mode="aspectFill" @tap.stop="chooseFaceImage"></image>
		<image v-else class="mine-face-image" :src="userDefaultFace" mode="aspectFit" @tap="toLogin"></image>
		<view class="mine-face-mask" @tap.stop="chooseFaceImage" v-if="!userInfo.avatar_id && userToken">
			<text class="suifont sui-shangchuan"></text>
			<text class="mine-face-mask-text">上传头像</text>
		</view>
		<image class="vip-sign" v-if="userInfo.is_vip" :src="userInfo.vip_file" @tap.stop="toPage" data-url="/pageUser/vip/log"></image>
	</view>
</template>

<script>
export default {
	data() {
		return {
			tempFilePath: ''
		};
	},
	mounted() {
		uni.$on('croperComplete', this.croperComplete);
	},
	beforeDestroy() {
		uni.$off('croperComplete', this.croperComplete);
	},
	computed: {},
	methods: {
		chooseFaceImage() {
			uni.chooseImage({
				count: 1,
				success: res => {
					this.navigateTo({
						url:
							'/pageSupport/supplement/cropper' +
							this.$u.queryParams({
								imagePath: res.tempFilePaths[0],
								viewToken: this.viewToken,
								aspectRatio: 1,
								initialBoxWidthRatio: 1,
								minBoxWidthRatio: 0.5
							})
					});
				}
			});
		},
		croperComplete(data) {
			if (data.fromToken === this.viewToken) {
				const dataRes = data.res;
				this.tempFilePath = dataRes.path;
				this.$u.api
					.uploadImage(dataRes.source, { param: JSON.stringify(dataRes.param) })
					.then(res => {
						console.log(res);
						this.$u.api
							.saveUserBasic({ avatar_id: res.data.file_id })
							.then(res => {
								setTimeout(() => {
									this.refreshUserInfo();
								}, 100);
							})
							.catch(e => {
								this.tempFilePath = '';
							});
					})
					.catch(e => {
						console.log(e);
						this.tempFilePath = '';
					});
			}
		},
		completeUserInfo(data) {
			this.tempFilePath = '';
		}
	}
};
</script>

<style lang="scss">
.mine-face {
	width: 140rpx;
	height: 140rpx;
	z-index: 1;
	position: relative;
	.mine-face-image {
		width: 140rpx;
		height: 140rpx;
		border-radius: 70rpx;
		background-color: #fff;
	}
	.vip-sign {
		width: 65rpx;
		height: 65rpx;
		position: absolute;
		bottom: 0;
		right: -30rpx;
	}
	.mine-face-mask {
		border-radius: 70rpx;
		position: absolute;
		width: 140rpx;
		height: 140rpx;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 20rpx;
		.suifont {
			font-size: 40rpx;
		}
		.mine-face-mask-text {
			font-size: 22rpx;
		}
	}
}
</style>
